package com.lwx.chapter11;

public class UnionFind2 implements UF {
    //元素对应的父节点
    //parent[i] 代表元素 i 指向的父节点
    private int[] parent;

    public UnionFind2(int size) {
        parent = new int[size];
        for (int i = 0; i < size; i++) {
            parent[i] = i;
        }
    }

    @Override
    public int getSize() {
        return parent.length;
    }

    //找到元素p对应的父节点
    private int find(int p){
        if(p < 0 || p > parent.length){
            throw new IllegalArgumentException("p is out of bound.");
        }
        while (p != parent[p]){
            p = parent[p];
        }
        return p;
//        if(p == parent[p]){
//            return parent[p];
//        }else {
//            return find(parent[p]);
//        }
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    //将p所在集合合并到q所在的集合
    @Override
    public void unionElements(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);
        if(pRoot == qRoot){
            return;
        }else {
            parent[pRoot] = qRoot;
        }
    }
}
